<template>
    <el-dialog class="jzb-dialog" :title="title" :visible.sync="visibleDialog" :width="width" id="dept-dialog-choose" :close-on-click-modal="false" append-to-body v-dialogDrag>
        <el-container class="mainer">
            <el-aside width="250px" class="jzb-area">
                <div class="hd">单位列表</div>
                <div class="hdflex h40"><el-input placeholder="搜索单位关键字" v-model="filterComText" size="mini"></el-input></div>
                <div class="bd">
                    <el-tree :data="comList" :props="comProps" @node-click="changeCom" node-key="comId" ref="comTree" :filter-node-method="filterComNode"></el-tree>
                </div>
            </el-aside>
            <el-aside width="500px" :class="['jzb-area',multiple?'':'flex1']" style="overflow-y:hidden;">
                <div class="hd">用户列表（{{selectComName.length>10?(selectComName.substring(0,10)+'...'):selectComName}}）</div>
                <div class="hdflex h40">
                    <el-input id="user-input-keywords" placeholder="关键字搜索" v-model="keywords" size="mini" style="width:250px;">
                        <i slot="suffix" class="el-input__icon el-icon-search" @click="GetUserList" id="user-search-keywords"></i>
                    </el-input>
                </div>
                <div class="bd">
                    <el-table id="user-table-selfuser" class="jzb-table" :data="userList" style="width: 100%;" size="mini" 
                        @row-click="clickRow" highlight-current-row  @select="selfSelectUser" @select-all="selfSelectUser" 
                        v-loading="loading" element-loading-text="拼命加载中" element-loading-background="rgba(0, 0, 0, 0.8)"
                        ref="userTable" :row-class-name="tableRowClassName" height="390">
                        <el-table-column type="index" class-name="index" width="30" :index="tableIndex"></el-table-column>
                        <el-table-column type="selection" class-name="selection" width="30" v-if="multiple"></el-table-column>
                        <el-table-column name="nickname" prop="nickname" label="姓名" width="90"></el-table-column>
                        <el-table-column name="username" prop="username" label="用户名"></el-table-column>
                        <el-table-column name="depart" label="部门" align="center" width="90">
                            <template slot-scope="scope">{{scope.row.depart?scope.row.depart.depName:''}}</template>
                        </el-table-column>
                        <el-table-column name="duties" prop="duties" label="职位" align="center" width="90"></el-table-column>
                    </el-table>
                </div>
                <div class="ft">
                    <myPagination @pageChange="GetUserList" :page="page"></myPagination>
                </div>
            </el-aside>
            <el-main class="jzb-colflex" v-if="multiple">
                <div class="hd">已选人员（{{choosedList.length}}）</div>
                <div class="bd pl-10 pr-10">
                    <el-tag-group v-model="choosedList" :isGroup="true" @change="initSelection" labelName="nickname" valueName="userId"></el-tag-group>
                </div>
            </el-main>
        </el-container>
        <el-footer height="auto" class="jzb-dialog-footer" slot="footer">
            <div class="content" v-if="multiple">已选人员：{{choosedList.length}}</div>
            <div class="content" v-else>已选人员：{{choosedUser?choosedUser.nickname:'未选中'}}</div>
            <button type="button" class="jzb-button" @click="saveData"><span class="icon icon-ok"></span>保 存</button>
            <button type="button" class="jzb-button" @click="visibleDialog = false"><span class="icon icon-undo"></span>取 消</button>
        </el-footer>
    </el-dialog>
</template>
<script>
/** 组件功能：从本单位和参建单位选择人员列表-v2
* 传入：props
* 输出：[{userId,nickname,comId,comName,...},...]
*/
import _ from 'lodash';
import elTagGroup from '@/components/public/el-tag-group.vue';
import myPagination from "@/components/public/myPagination.vue";
import {GetRequestParams,toJson} from "@/utils/utils.js";
import {user,company} from "@/api/org.js";
export default {
    name:'com-choose-user',
    components: {
         myPagination,elTagGroup,
    },
    props:{
        // 配置项
        comId:{ type: String, default: '' }, //单位ID
        projId:{ type: String, default: '' }, //查单位列表：范围缩小到参与了项目的参建单位
        contId:{ type: String, default: '' }, //查单位列表：范围缩小到参与了合同的参建单位
        userId:{ type: String, default: '' }, //查单位列表：范围缩小到用户加入的参建单位
        title:{ type: String, default: '选择人员' }, //对话框title
        visible:{ type: Boolean, default: false }, //对话框显示
        ifInit:{ type: Boolean, default: false }, //是否初始化本单位信息
        width:{ type: String, default: '1100px' }, //对话框宽度
        value:{ default:null}, //用户列表默认选中
        multiple:{ type: Boolean, default:false}, //单选还是多选 true返回数组，false返回单个对象
        returnValue:{ type: Boolean, default:false}, //是否必须选中值
    },
    data(){
        return {
            //用户
            choosedList:[],
            choosedUser:null,
            page:{ pageCurrent: 1, pageSize: 50, total: 0, }, //分页
            keywords:'',
            userList:[],
            dataList:[],
            ifInitUser:false,
            loading:false,
            //单位
            selectComId:'',
            selectComName:'',
            comList:[],
            comProps:{
                value:'comId',             // ID字段名
                label: 'comName',         // 显示名称
                children: 'children'    // 子级字段名
            },
            filterComText:'',
            //基本
            visibleDialog:false,
        };
    },    
    watch:{
        value(val){
            if(this.multiple){
                this.dataList = [...val];
            }else{
                this.choosedUser = val;
            }
        },
        visible(val){
            if(val) this.openComChooseData();
        },
        visibleDialog(val){
            if(!val) this.$emit('close');
        },
        filterComText(val) {
            this.$refs.comTree.filter(val.trim());
        },
        comId(val){
            this.selectComId=val||this.$store.state.comId||GetRequestParams().comid;
            let com = this.comList.find(item=>item.comId==val)
            if(com) this.selectComName = com.comName;
            this.GetUserList();
        },
        projId(val){
            this.GetBudComList();
        },
        contId(val){
            this.GetBudComList();
        },
    },
    mounted(){
        if(this.ifInit){
            this.GetBudComList();
            this.GetUserList();
            this.ifInitUser=true;
        }
    },
    methods:{
        //1.1 组件打开时初始化
        openComChooseData(){
            if(this.multiple){
                this.choosedList = [...this.dataList];
                this.choosedUser = null;
            }else{
                this.choosedUser = this.value;
                this.choosedList = [];
            }
            this.visibleDialog = true;
            if(!this.ifInitUser){
                this.ifInitUser=true;
                this.GetBudComList();
            }else{
                this.initSelection();
            }
        },
        //2.1 获取参建单位+本单位列表
        GetBudComList(){
            let params = {
                comId:this.$store.state.comId||GetRequestParams().comid,
                includeSelf:true,
            }
            if(this.projId) params.projId = this.projId;
            if(this.contId) params.contId = this.contId;
            company.listBudBrief(params).then(res=>{
                if(res.code='30000'){
                    this.comList = [res.com,...res.buds];
                    this.selectComId = this.comId||params.comId;
                    this.selectComName = this.comList.find(item=>item.comId==this.selectComId).comName;
                    this.GetUserList();
                }
            })
        },
        //2.2 切换单位时
        changeCom(node){
            this.selectComId = node.comId;
            this.selectComName = node.comName;
            this.GetUserList();
        },
        //2.6 关键字搜索
        filterComNode(value, data) {
            if (!value) return true;
            return data.comName.indexOf(value) !== -1;
        },
        //3.1 获取用户列表
        GetUserList(){
            let params = {
                comId:this.selectComId,
                jobScope: 'IN_JOB',
                keywords:this.keywords.trim(),
                page: this.page.pageCurrent,
                size: this.page.pageSize,
                fetchCom:true,
            }
            this.loading=true;
            user.listPaged(params).then(res=>{
                this.loading=false;
                if(res.code='30000'){
                    this.userList = res.records.map(item=>{
                        item.comId = item.com.comId;
                        item.comName = item.com.comName;
                        return item;
                    })
                    this.page.total = res.total;
                    setTimeout(() => { this.initSelection(); },200);
                }
            })
        },
        //3.2 用户序号
        tableIndex(number){
            return (this.page.pageCurrent-1)*this.page.pageSize+number+1;
        },
        //3.3 初始化选中用户
        initSelection() {
            if(!this.$refs.userTable){
                setTimeout(() => { this.initSelection(); },300);
                return;
            } 
            if(this.$refs.userTable){
                this.$refs.userTable.clearSelection();
                this.userList.forEach(row =>{
                    if(this.choosedList.some(item=>item.userId==row.userId)) this.$refs.userTable.toggleRowSelection(row ,true);
                })
            }   
        },
        //3.4 本单位复选框事件: choosedList = choosedList -userList + selection
        selfSelectUser(selection){
            this.choosedList = _.pullAllBy(this.choosedList, this.userList, 'userId')
            this.choosedList = _.uniqBy(_.concat(this.choosedList, selection), 'userId'); 
        },
        //3.5 选中行
        clickRow(row, column, event){
            if(this.multiple){
                this.$refs.userTable.toggleRowSelection(row);
                let choosedList = this.choosedList.some(item=>item.userId==row.userId)?_.pullAllBy(this.choosedList, [row],'userId'):_.concat(this.choosedList, row);
                this.choosedList =[...choosedList];
            }else{
                this.choosedUser = row;
            }
        },
        //3.6 选中行样式
        tableRowClassName({row, rowIndex}){
            if(this.multiple){
                return this.choosedList.some(item=>item.userId===row.userId)?'selected-row':'un-selected-row';
            }else{
                return '';
            }
        },
        //4.保存数据
        saveData(){
            if(this.returnValue && (this.choosedList.length==0 && !this.choosedUser) ){
                this.$layer.msg('请选择用户');
                return;
            }
            if(this.multiple){
                this.$emit('input',this.choosedList);
                this.$emit('change',this.choosedList);
            }else{
                console.log(this.choosedUser)
                this.$emit('input',this.choosedUser);
                this.$emit('change',this.choosedUser);
            }
            this.visibleDialog = false;
        },
    },
};
</script>
<style lang="less" scoped>
@import "~@/assets/style/base.css";
@import "~@/assets/style/common.less";
.mainer{min-height:500px;overflow:auto;border:1px solid #ddd;}
.jzb-area.flex1{flex:1;}
</style>